package com.bdh.javaBasicStudy;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;

/**
 * @projectName: maven_project
 * @package: com.bdh.javaBasicStudy
 * @className: StringClassExer
 * @author: Dream
 * @description:
 * https://blog.csdn.net/Dream__Y/article/details/122724539 学习时写的博客
 * String/StringBuffer相关类练习
 * @date: 2022/6/16 18:01
 */
public class StringClassExer {
    @Test
    public void testAltho(){
        //请实现一个函数，把字符串 s 中的每个空格替换成"%20"。
        String s = "We are Happy";
        System.out.println(replaceSpace(s));

        String s1 = "the sky is blue";
        System.out.println(reverseWords(s1));

    }

    public String replaceSpace(String s) {
        StringBuffer stringBuffer = new StringBuffer(s);
        for (int i = 0; i < s.length(); i++) {
            if(stringBuffer.charAt(i) == ' '){
                stringBuffer.replace(i, i+1, "%20");
            }
        }
        return stringBuffer.toString();
    }

    public String reverseWords(String s) {
        StringBuffer res = new StringBuffer(StringUtils.trimToEmpty(s));
        res.reverse();
        for (int i = 0; i < res.length(); i++) {
            if(res.charAt(i) == ' '){
                while(i+1 < res.length() && res.charAt(i+1) == ' '){
                    res.deleteCharAt(i++);
                }
            }
        }
        reverseEachWord(res);
        return res.toString();
    }
    public void reverseString(StringBuffer sb, int start, int end){
        while (start < end){
            char temp = sb.charAt(start);
            sb.setCharAt(start++, sb.charAt(end));
            sb.setCharAt(end--, temp);
        }
    }
    public void reverseEachWord(StringBuffer sb){
        int start = 0;
        int end = 1;
        int n = sb.length();
        while(start < n){
            while(end < n && sb.charAt(end) != ' '){
                end++;
            }
            reverseString(sb, start, end - 1);
            start = end + 1;
            end = start + 1;
        }
    }
}
